<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'
import { batchAddResidents } from '@/api/owner/resident'

const route = useRoute()
const router = useRouter()

// 基础信息
const baseInfo = reactive({
  ownerId: null,
  houseDisplay: '', // 添加房屋显示信息
  ownerName: '',    // 业主姓名
  idCard: '',       // 身份证号
  ownerType: '', // 业主类型，默认为户主
  phone: ''         // 手机号
})

const batchFormRef = ref(null)

// 动态成员列表
const batchForm = reactive({
  members: [
    { name: '', phone: '', idCard: '', relation: '' }
  ]
})

// 关系选项
const relationOptions = [
  { label: '家属', value: '家属' },
  { label: '租户', value: '租户' }
]

// 添加成员行
const addMemberRow = () => {
  batchForm.members.push({ name: '', phone: '', idCard: '', relation: '' })
}

// 删除成员行
const removeMemberRow = (index) => {
  if (batchForm.members.length > 1) {
    batchForm.members.splice(index, 1)
  } else {
    // 如果只剩一行，清空数据而不是删除
    batchForm.members[0] = { name: '', phone: '', idCard: '', relation: '' }
  }
}

// 验证单个成员是否完整
const validateMember = (member) => {
  const { name, phone, idCard, relation } = member
  return name.trim() && phone.trim() && idCard.trim() && relation
}

// 验证单个成员是否部分填写
const isPartiallyFilled = (member) => {
  const { name, phone, idCard, relation } = member
  const filledFields = [
    name.trim(),
    phone.trim(),
    idCard.trim(),
    relation
  ].filter(Boolean).length

  return filledFields > 0 && filledFields < 4
}

// 验证手机号格式
const validatePhone = (phone) => {
  return /^1[3-9]\d{9}$/.test(phone)
}

// 验证身份证号格式
const validateIdCard = (idCard) => {
  return /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(idCard)
}

// 保存
const handleSave = async () => {
  // 检查业主ID是否存在
  if (!baseInfo.ownerId) {
    ElMessage.error('业主信息不存在，请重新选择业主')
    return
  }

  // 检查是否有部分填写的行
  let hasPartialData = false
  let hasFormatError = false

  for (let i = 0; i < batchForm.members.length; i++) {
    const member = batchForm.members[i]

    if (isPartiallyFilled(member)) {
      ElMessage.warning(`第${i + 1}行成员信息不完整，请填写完整或删除该行`)
      hasPartialData = true
      break
    }

    // 如果成员信息完整，验证格式
    if (validateMember(member)) {
      if (!validatePhone(member.phone)) {
        ElMessage.warning(`第${i + 1}行手机号格式不正确`)
        hasFormatError = true
        break
      }

      if (!validateIdCard(member.idCard)) {
        ElMessage.warning(`第${i + 1}行身份证号格式不正确`)
        hasFormatError = true
        break
      }
    }
  }

  if (hasPartialData || hasFormatError) {
    return
  }

  // 只收集有完整数据的成员
  const submitData = []
  batchForm.members.forEach(member => {
    if (validateMember(member)) {
      submitData.push({
        ownerId: baseInfo.ownerId,
        name: member.name.trim(),
        phone: member.phone.trim(),
        idCard: member.idCard.trim(),
        relationship: member.relation
      })
    }
  })

  console.log('提交的数据:', submitData)

  if (submitData.length === 0) {
    ElMessage.warning('请至少填写一个完整的成员信息')
    return
  }

  try {
    // 调用API保存数据
    debugger
    const response = await batchAddResidents(submitData)
    ElMessage.success(response.msg || `成功添加 ${submitData.length} 个成员`)
    handleReset();
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error(error.response.data.msg || '保存失败')
  }
}

// 重置
const handleReset = () => {
  // 重置为一行空数据
  batchForm.members = [
    { name: '', phone: '', idCard: '', relation: '' }
  ]

  // 清除表单验证
  if (batchFormRef.value) {
    batchFormRef.value.clearValidate()
  }
}

// 页面加载时初始化数据
onMounted(() => {
  // 设置业主信息
  if (route.query.ownerName) {
    baseInfo.ownerName = route.query.ownerName
  }
  if (route.query.ownerId) {
    baseInfo.ownerId = route.query.ownerId
  }
  if (route.query.idCard) {
    baseInfo.idCard = route.query.idCard
  }
  if (route.query.phonenumber) {
    baseInfo.phone = route.query.phonenumber
  }
  if (route.query.ownerType){
    baseInfo.ownerType = route.query.ownerType
  }

  // 构建房屋显示信息
  const houseParts = []
  if (route.query.communityName) houseParts.push(route.query.communityName)
  if (route.query.buildingName) houseParts.push(route.query.buildingName)
  if (route.query.unitCount) houseParts.push(`${route.query.unitCount}单元`)
  if (route.query.roomNo) houseParts.push(route.query.roomNo)

  if (houseParts.length > 0) {
    baseInfo.houseDisplay = houseParts.join('-')
  }
})
</script>

<template>
  <div class="member-register">
    <div class="header">
      <h2>房屋成员登记</h2>
    </div>

    <div class="content">
      <!-- 基础信息 -->
      <el-card class="section-card">
        <template #header>
          <div class="card-header">
            <span class="section-title">基础信息</span>
          </div>
        </template>

        <div class="base-info-grid">
          <div class="form-row">
            <div class="form-item">
              <label class="form-label">*关联房屋：</label>
              <el-input
                  v-model="baseInfo.houseDisplay"
                  placeholder="房屋信息"
                  readonly
              />
            </div>
            <div class="form-item">
              <label class="form-label">*业主姓名：</label>
              <el-input
                  v-model="baseInfo.ownerName"
                  placeholder="业主姓名"
                  readonly
              />
            </div>
          </div>

          <div class="form-row">
            <div class="form-item">
              <label class="form-label">*业主身份证号：</label>
              <el-input
                  v-model="baseInfo.idCard"
                  placeholder="业主身份证号"
                  readonly
              />
            </div>
            <div class="form-item">
              <label class="form-label">*业主类型：</label>
              <el-input
                  v-model="baseInfo.ownerType"
                  placeholder="业主类型"
                  readonly
              />
            </div>
          </div>

          <div class="form-row">
            <div class="form-item">
              <label class="form-label">*业主手机号：</label>
              <el-input
                  v-model="baseInfo.phone"
                  placeholder="业主手机号"
                  readonly
              />
            </div>
          </div>
        </div>
      </el-card>

      <!-- 批量新增成员 -->
      <el-card class="section-card">
        <template #header>
          <div class="card-header">
            <div class="header-left">
              <span class="section-title">新增成员</span>
            </div>
            <div class="header-right">
              <el-button type="primary" :icon="Plus" @click="addMemberRow">
                添加成员
              </el-button>
            </div>
          </div>
        </template>

        <div class="batch-form-content">
          <!-- 表头 -->
          <div class="form-header">
            <div class="header-item">成员姓名</div>
            <div class="header-item">手机号码</div>
            <div class="header-item">身份证号</div>
            <div class="header-item">户主关系</div>
            <div class="header-item">操作</div>
          </div>

          <!-- 动态成员行 -->
          <div
              v-for="(member, index) in batchForm.members"
              :key="index"
              class="form-row"
          >
            <div class="form-item">
              <el-input
                  v-model="member.name"
                  placeholder="请输入姓名"
                  class="form-input"
              />
            </div>
            <div class="form-item">
              <el-input
                  v-model="member.phone"
                  placeholder="请输入手机号"
                  class="form-input"
              />
            </div>
            <div class="form-item">
              <el-input
                  v-model="member.idCard"
                  placeholder="请输入身份证号"
                  class="form-input"
              />
            </div>
            <div class="form-item">
              <el-select
                  v-model="member.relation"
                  placeholder="请选择关系"
                  class="form-input"
              >
                <el-option
                    v-for="item in relationOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </div>
            <div class="form-item operation-item">
              <el-button
                  type="danger"
                  :icon="Delete"
                  @click="removeMemberRow(index)"
                  :disabled="batchForm.members.length === 1 && !member.name && !member.phone && !member.idCard && !member.relation"
              >
                删除
              </el-button>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button type="primary" @click="handleSave">
          保存
        </el-button>
        <el-button @click="handleReset">
          重置
        </el-button>
        <el-button @click="router.back()">
          返回
        </el-button>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.member-register {
  padding: 20px;
  background: white;
  min-height: 100vh;

  .header {
    margin-bottom: 20px;

    h2 {
      margin: 0;
      color: #303133;
      font-size: 20px;
      font-weight: 600;
    }
  }

  .content {
    max-width: 1200px;
  }

  .section-card {
    margin-bottom: 24px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .section-title {
        font-size: 16px;
        font-weight: 600;
        color: #303133;
      }
    }
  }

  .base-info-grid {
    .form-row {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 24px;
      margin-bottom: 20px;
      align-items: start;

      .form-item {
        display: flex;
        flex-direction: column;

        .form-label {
          margin-bottom: 8px;
          color: #606266;
          font-size: 14px;
          font-weight: 600;
          line-height: 1.5;
        }

        .el-input,
        .el-select {
          width: 100%;
        }
      }
    }
  }

  .batch-form-content {
    .form-header {
      display: grid;
      grid-template-columns: 1fr 1fr 1fr 1fr 120px;
      gap: 16px;
      margin-bottom: 16px;
      padding: 0 8px;

      .header-item {
        color: #606266;
        font-size: 14px;
        font-weight: 600;
        text-align: center;

        &:last-child {
          text-align: center;
        }
      }
    }

    .form-row {
      display: grid;
      grid-template-columns: 1fr 1fr 1fr 1fr 120px;
      gap: 16px;
      margin-bottom: 16px;
      align-items: start;

      .form-item {
        .form-input {
          width: 100%;
        }

        &.operation-item {
          display: flex;
          align-items: center;
          justify-content: center;

          .el-button {
            width: 100%;
            // 和其他输入框保持一致的高度
            height: 32px;
          }
        }
      }
    }
  }

  .action-buttons {
    text-align: center;
    padding: 30px 0;

    .el-button {
      margin: 0 12px;
      min-width: 80px;
      padding: 10px 24px;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .member-register {
    padding: 16px;

    .base-info-grid .form-row {
      grid-template-columns: 1fr;
      gap: 16px;
    }

    .batch-form-content .form-header,
    .batch-form-content .form-row {
      grid-template-columns: 1fr;
      gap: 12px;
    }

    .action-buttons {
      padding: 24px 0;

      .el-button {
        margin: 0 8px 8px 0;
        padding: 8px 20px;
      }
    }
  }
}
</style>